﻿using System;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.ServiceProcess;

namespace DelegateService
{
    public partial class DelegateService : ServiceBase
    {
        private Process _process;

        public DelegateService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            var exePath = ConfigurationManager.AppSettings["Path"];
            var arguments = ConfigurationManager.AppSettings["Arguments"];

            var workingDir = Path.GetDirectoryName(exePath);

            if(workingDir == null)
                throw new InvalidOperationException("No directory found.");

            _process = new Process
            {
                StartInfo = new ProcessStartInfo(exePath)
                {
                    WorkingDirectory = workingDir,
                    UseShellExecute = true,
                    Arguments = arguments
                }
            };

            _process.Start();
        }

        protected override void OnStop()
        {
            if (_process != null)
                _process.Kill();

            _process = null;
        }
    }
}
